package indi.zhifa.core.multidatasource.core;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;

@Slf4j
public class MultiDataSourceConfigurerRegister implements ImportBeanDefinitionRegistrar,
        EnvironmentAware, ResourceLoaderAware, BeanFactoryAware {

    private Environment mEnvironment;
    private ResourceLoader mResourceLoader;
    private BeanFactory mBeanFactory;

    public MultiDataSourceConfigurerRegister() {
    }


    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
                                        BeanDefinitionRegistry registry,
                                        BeanNameGenerator importBeanNameGenerator) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MultiDataSourceConfigurer.class);
        builder.addConstructorArgValue(mBeanFactory);
        builder.addConstructorArgValue(mResourceLoader);
        builder.addConstructorArgValue(mEnvironment);
        builder.addConstructorArgReference("routingDataSourceMemo");
        registry.registerBeanDefinition(MultiDataSourceConfigurer.class.getName(),builder.getBeanDefinition());
    }

    @Override
    public void setEnvironment(Environment pEnvironment) {
        mEnvironment = pEnvironment;
    }

    @Override
    public void setResourceLoader(ResourceLoader pResourceLoader) {
        mResourceLoader = pResourceLoader;
    }

    @Override
    public void setBeanFactory(BeanFactory pBeanFactory) throws BeansException {
        mBeanFactory = pBeanFactory;
    }
}
